package model

import (
	"time"
	"gorm.io/gorm"
)

type Inventory struct {
	Id         int64     `json:"id" gorm:"primaryKey;autoIncrement"`
	FuelType   string    `json:"fuelType" gorm:"uniqueIndex;size:50;not null"`
	Stock      float64   `json:"stock" gorm:"type:decimal(15,2);not null;default:0"`
	MinStock   float64   `json:"minStock" gorm:"type:decimal(15,2);not null;default:1000"`
	MaxStock   float64   `json:"maxStock" gorm:"type:decimal(15,2);not null;default:50000"`
	CreateTime time.Time `json:"createTime" gorm:"autoCreateTime"`
	UpdateTime time.Time `json:"updateTime" gorm:"autoUpdateTime"`
}

func (Inventory) TableName() string {
	return "inventory"
}

type InventoryModel struct {
	db *gorm.DB
}

func NewInventoryModel(db *gorm.DB) *InventoryModel {
	return &InventoryModel{db: db}
}

func (m *InventoryModel) FindAll() ([]Inventory, error) {
	var inventories []Inventory
	err := m.db.Find(&inventories).Error
	return inventories, err
}

func (m *InventoryModel) UpdateStock(id int64, stock float64) (*Inventory, error) {
	var inventory Inventory
	err := m.db.Model(&inventory).Where("id = ?", id).Update("stock", stock).Error
	if err != nil {
		return nil, err
	}
	
	err = m.db.First(&inventory, id).Error
	return &inventory, err
}

func (m *InventoryModel) FindById(id int64) (*Inventory, error) {
	var inventory Inventory
	err := m.db.First(&inventory, id).Error
	return &inventory, err
}